import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/store/modules/user'
import router from '@/router'

const contentType = 'application/json;charset=UTF-8'

const request = axios.create({
  baseURL: import.meta.env.VITE_SERVE,
  timeout: 1000 * 50, // 超时时间
  withCredentials: true,
  headers: {
    'Content-Type': contentType,
  },
})

request.interceptors.request.use((config) => {
  //获取用户相关的小仓库:获取仓库内部token,登录成功以后携带给服务器
  const userStore = useUserStore()
  
  if (userStore.token) {
    // config.headers['Access-Token'] = userStore.token
  }
  //config配置对象,headers属性请求头,经常给服务器端携带公共参数
  //返回配置对象
  return config
})
request.interceptors.response.use(
  (response) => {
    //成功回调
    //简化数据
    return response.data
  },
  (error) => {
    //失败回调:处理http网络错误的
    //定义一个变量:存储网络错误信息
    let message = ''
    //http状态码
    const status = error.response?.status
    const msg = error.response?.data?.message
    message = msg
    
    switch (status) {
      case 300:
        message = msg || '数据问题'
        break
      case 401:
        const userStore = useUserStore()
        userStore.removeLoginCache()
        // router.push('/')
        message = msg || 'TOKEN过期'
        break
      case 403:
        message = msg || '无权访问'
        break
      case 404:
        message = msg || '请求地址错误'
        break
      case 500:
        message = msg || '服务器出现问题'
        break
      default:
        message = msg || '网络出现问题'
        break
    }
    //提示错误信息
    // ElMessage({
    //   type: 'error',
    //   message,
    // })
    return Promise.reject(error)
  },
)

export default request
